package com.system.servlet;

import com.ramostear.captcha.HappyCaptcha;
import com.system.pojo.User;
import com.system.service.BookService.BookService;
import com.system.service.BookService.BookServiceImpl;
import com.system.service.UserService.UserService;
import com.system.service.UserService.UserServiceImpl;
import com.system.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userCode = req.getParameter("UserCode");
        String userPsw = req.getParameter("UserPsw");

        UserService userService = new UserServiceImpl();

        /*验证码*/
        String code = req.getParameter("code");
        boolean flag = HappyCaptcha.verification(req,code,true);

        try {
            User user = userService.Login(userCode,userPsw);
            if(user!=null && userCode.equals(user.getUserCode()) && userPsw.equals(user.getUserPsw()) && flag){
                HappyCaptcha.remove(req);
                System.out.println("登录成功！");
                System.out.println("UserImgPath: "+user.getUserImgPath());
                req.setAttribute("UserImgPath",user.getUserImgPath());
                req.getSession().setAttribute(Constant.USER_SESSION,user);
                System.out.println("flag:"+flag);
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }else{
                HappyCaptcha.remove(req);
                String msg = null;
                msg = "登陆失败";
                System.out.println("登录失败！");
                System.out.println("flag:"+flag);
                req.setAttribute("msg",msg);
                resp.sendRedirect("index.jsp");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
